﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Web;
using YunZuan.Models;

namespace Yunzuan.Common
{
    public class CommonUrl
    {    
        public static string getURL(HashParam hsParam,string strParam, string msg="")
        {
            try
            {
                CommonUrl cu = new CommonUrl();
                if (strParam == ""&& hsParam == null) return "";
                if (hsParam == null) //有些用page或者直接实体类的则hashparam传了null
                    hsParam = JsonConvert.DeserializeObject<HashParam>(strParam.Trim());
                 
                var key = hsParam.GetString("TagKey");
                if (hsParam.ContainsKey("OperationUserId"))
                { 
                    var activeIP= hsParam.GetString("ActiveIP"); 
                    if (msg.Contains("登陆"))
                    {
                        if (System.Web.HttpContext.Current.Cache.Get("Cache:key" + key + activeIP) == null)
                        {
                            System.Web.HttpContext.Current.Cache.Insert("Cache:key" + key + activeIP, activeIP, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(2));
                        }
                        else
                        {
                            //添加黑名单
                            cu.AddBlackList(key, activeIP);
                            ConmonMQMsgClass.send(msg + "操作频繁" + strParam);
                            return "";
                        }
                    }
                  
                }
                if (msg != "")
                {
                    if (msg == "查询库存")
                    {
                        if (hsParam.ContainsKey("weight") || hsParam.ContainsKey("weightMin") || hsParam.ContainsKey("weightMax") || hsParam.ContainsKey("Shape")
                            || hsParam.ContainsKey("Color") || hsParam.ContainsKey("Clarity") || hsParam.ContainsKey("Cut")
                            || hsParam.ContainsKey("Polish") || hsParam.ContainsKey("Symmetry") || hsParam.ContainsKey("Fluorescence")
                            || hsParam.ContainsKey("alias"))
                        { 
                            var operationUserId = hsParam.ContainsKey("OperationUserId") ? hsParam.GetString("OperationUserId") : ""; 
                            var type = 0;
                            if ((hsParam.ContainsKey("CustomerID") && hsParam.GetString("CustomerID") != "" && !hsParam.ContainsKey("UserID")) || operationUserId.Contains("客户"))
                            {
                                type = 2;
                            }
                            else if (operationUserId.Contains("团队"))
                                type = 1; 

                            string userNameMobile = "";
                            string userId = operationUserId.Replace("团队", "").Replace("客户", "").TrimEnd(','); 
                            if (userId != "")
                                userNameMobile = GetMobile(type, userId, key);
                            else
                            {
                                if (hsParam.ContainsKey("CustomerID") && hsParam.GetString("CustomerID") != "")
                                {
                                    msg = "开放接口查询";
                                    userNameMobile = GetMobile(2, hsParam.GetString("CustomerID"), key);
                                }
                            }
                            if (userNameMobile == "") return key;
                            string userName = userNameMobile == "" ? "" : userNameMobile.Split(',')[0];
                            string Mobile = userNameMobile == "" ? "" : userNameMobile.Split(',')[1];
                            hsParam["OperationMobile"]= Mobile;
                            hsParam["userName"]= userName;
                            var _param = JsonConvert.SerializeObject(hsParam);
                            string strP = _param;
                            ConmonMQMsgClass.send(msg + strP);
                        }
                    }
                    else
                    { 
                        ConmonMQMsgClass.send(msg + strParam);
                    }
                } 
                //Yunzuan.Foundation.Log.Logger.Info(typeof(CommonUrl), string.Format("Supplier:{0},FullName:{1},MethodName:{2},before replace:{3},alter replace:{4}", key, sf.GetMethod().ReflectedType.FullName, sf.GetMethod().Name, _param, param));
                {
                    hsParam.Remove("ActiveIP");
                    hsParam.Remove("OperationUserId");
                    hsParam.Remove("HttpUrl");
                    hsParam.Remove("Browser");
                    hsParam.Remove("OpeartionSystem");
                    hsParam.Remove("TagKey");
                } 
                GlobalConfig.reLoadKey(key);
                return key;

            }
            catch (Exception ee)
            {
                IList<HashParam> param = JsonConvert.DeserializeObject<IList<HashParam>>(strParam);
                 
                GetMethodInfoAndWriteLogs(ee);
                return param[param.Count() - 1]["TagKey"].ToString();
                throw ee;
            }
            
        }

        
        /// <summary>
        /// 添加黑名单
        /// </summary>
        /// <param name="key"></param>
        public void AddBlackList(string key,string activeIP)
        {
            try
            {
                BlackList blacklist = YZ.GetDatabase(key).QueryForObject<BlackList>("BlackList.CheckIP", activeIP);
                if (blacklist == null)
                {
                    blacklist = new BlackList();
                    blacklist.ActiveIP = activeIP;
                    blacklist.createTime = DateTime.Now;
                    blacklist.status = 0;
                    blacklist.times = 10;
                    YZ.GetDatabase(key).Add(blacklist);
                }
                else
                {
                    blacklist.times += 1;
                    blacklist.updateTime = DateTime.Now;
                    YZ.GetDatabase(key).Edit(blacklist);
                    System.Web.HttpContext.Current.Cache.Insert("Cache:key" + key + activeIP, activeIP, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(blacklist.times*2));
                }
            }
            catch (Exception ee)
            {
                GetMethodInfoAndWriteLogs(ee);
                throw;
            } 
        }
        public static int GetTimes(string key, string IP)
        {
            try
            {
                BlackList blacklist = YZ.GetDatabase(key).QueryForObject<BlackList>("BlackList.CheckIP", IP);
                if (blacklist != null)
                {
                    return blacklist.times*2;
                }
                return 0;
            }
            catch (Exception ee)
            {
                GetMethodInfoAndWriteLogs(ee);
                throw; 
            } 
        }
        /// <summary>
        /// 清空过期时间
        /// </summary>
        /// <param name="key"></param>
        public static void DelTimes(string key, string IP)
        {
            try
            {
                BlackList blacklist = YZ.GetDatabase(key).QueryForObject<BlackList>("BlackList.CheckIP", IP); 
                if(blacklist !=null)
                {
                    blacklist.times =0;
                    blacklist.updateTime = DateTime.Now;
                    YZ.GetDatabase(key).Edit(blacklist); 
                }
            }
            catch (Exception ee)
            {
                GetMethodInfoAndWriteLogs(ee);
                throw;
            } 
        }
        /// <summary>
        /// 获取用户名|电话号码
        /// </summary>
        /// <param name="type"></param>
        /// <param name="userId"></param>
        /// <param name="tttagKey"></param>
        /// <returns></returns>
        public static string GetMobile(int type, string userId, string tttagKey)
        {
            try
            {
                int.TryParse(userId, out int result); 
                if (result > 0)
                {
                    if (type == 1 && !string.IsNullOrEmpty(userId))//团队
                    {
                        UserInfo userInfo = YZ.GetDatabase(tttagKey).Get<UserInfo>(int.Parse(userId));
                        if (userInfo != null)
                            return userInfo.UserName+","+ userInfo.Mobile;
                    }
                    else if (type == 2 && !string.IsNullOrEmpty(userId))//客户
                    {
                        CustomerInfo userInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(int.Parse(userId));
                        if (userInfo.SearchDate == null)
                        {
                            userInfo.SearchDate = DateTime.Now;
                        }
                        else
                        {
                            if (userInfo.SearchDate.Value.ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))
                            {
                                userInfo.SearchDate = DateTime.Now;
                                userInfo.SearchCountFlag = 1;
                                userInfo.SearchCount = 0;
                            }
                        }
                        //不限制二级网站查询
                        if (string.IsNullOrEmpty(userInfo.CustomerKey))
                        {
                            if (userInfo != null && userInfo.SysStatus == 1)
                            {
                                userInfo.SearchCount = userInfo.SearchCount + 1;
                                if (userInfo.SearchCount > GlobalConfig.SearchCount)
                                {
                                    userInfo.SearchCountFlag = 0;
                                }
                                else
                                {
                                    userInfo.SearchCountFlag = 1;
                                }
                                YZ.GetDatabase(tttagKey).Edit(userInfo);
                                return userInfo.UserName + "," + userInfo.Mobile;
                            }
                        }
                        else
                        {
                            return userInfo.UserName + "," + userInfo.Mobile;
                        }
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ee)
            {
                GetMethodInfoAndWriteLogs(ee);
                throw;
            }
            return "";
        }



        /// <summary>
        /// 得到当前方法并记录日志
        /// </summary>
        /// <param name="ex"></param>
        public static void GetMethodInfoAndWriteLogs(Exception ex = null, string msg = "")
        {
            var type = typeof(CommonUrl);
            try
            {
                StackTrace st = new StackTrace(true);
                MethodBase mb = st.GetFrame(1).GetMethod();
                var line = "";
                var errInfo = "";
                var paramName0 = "";//记录第一个参数名
                if (ex != null) //有些错误信息没有行号，导致什么信息都没有记录
                {
                    if (ex.StackTrace.IndexOf("行号") > -1)
                        line = ex.StackTrace.Substring(ex.StackTrace.IndexOf("行号"), ex.StackTrace.Length - ex.StackTrace.IndexOf("行号")); //行号
                    errInfo = ex.Message;
                }
                //取得父参数名
                if (mb.GetParameters().Count() > 0)
                {
                    paramName0 = mb.GetParameters()[0].Name;
                }
                //var logTemplate = string.Format(_logTemplate, mb.Name, paramName0, line, logParam);
                
            }
            catch (Exception e)
            { 
                GetMethodInfoAndWriteLogs(e); 
                throw;
            }
        }

        
    }


}
